﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using DataContexts.Supplier;

public partial class Admin_addEditLocation : System.Web.UI.Page
{
    private SupplierDataContext supplierContext = new SupplierDataContext();

    public int LocationId
    {
        get
        {
            return Helper.QSIntValue("id");
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        ((BaseMasterPage)this.Master).CurrentPage = PageConfig.Pages.AdminLocationAddEdit;
        if (!((BaseMasterPage)this.Master).AuthorizeCurrentUser())
            return;

        if (!Page.IsPostBack)
        {
            LoadRegionDropDown();

            if (LocationId > 0)
            {
                Location location = supplierContext.Locations.SingleOrDefault(obj => obj.LocationId== LocationId);
                //CONTROL ASSIGNMENT
                txtLocationName.Text = location.LocationName;
                txtLocationCode.Text = location.LocationCode;
                ddlRegion.SelectedValue = location.RegionId.Value.ToString();
                chkActive.Checked = location.Active.Value;
            }
        }
    }

    private void LoadRegionDropDown()
    {
        ddlRegion.DataSource = from r in supplierContext.Regions
                               select r;
        ddlRegion.DataTextField = "RegionName";
        ddlRegion.DataValueField = "RegionId";
        ddlRegion.DataBind();

        ddlRegion.Items.Insert(0, new ListItem("--Select Region--", "0"));
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            Location location = new Location();
            if (LocationId > 0)
                location = supplierContext.Locations.SingleOrDefault(obj => obj.LocationId == LocationId);

            //PROPERTY ASSIGNMENT
            location.LocationName= txtLocationName.Text;
            location.LocationCode = txtLocationCode.Text;
            location.RegionId= Convert.ToInt32(ddlRegion.SelectedValue);
            location.Active = chkActive.Checked;

            if (LocationId == 0)
                supplierContext.Locations.InsertOnSubmit(location);

            supplierContext.SubmitChanges();

            Response.Redirect("ViewLocations.aspx");
        }
    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("ViewLocations.aspx");
    }
    protected void cvRegion_ServerValidate(object source, ServerValidateEventArgs args)
    {
        if (ddlRegion.SelectedIndex == 0)
        {
            args.IsValid = false;
        }
    }
}
